import { ref, onMounted } from 'vue'

// ------------------------------ 接口类型 ------------------------------
interface IParams {
  pageNo?: number
  pageSize?: number
}
interface IResponseData {
  records: Array<any>
  total: number
}

/**
 *
 * @param queryByPage 请求函数
 */
// ------------------------------ 分页 ------------------------------
export const usePagination = <T extends IResponse<IResponseData>>(
  queryByPage: (params: IParams) => Promise<T>
) => {
  // 当前页
  const pageNo = ref(1)
  // 可供选择的分页大小
  const pageSizes = ref([5, 10, 15])
  // 当前页分页大小
  const pageSize = ref(5)
  // 总数
  const pageTotal = ref(0)
  // 问题解决：http://imyhq.com/design/20405.html
  // 表格数据
  const tableData = ref<Array<IResponseData>>()
  // 加载状态
  const tableLoad = ref(false)

  // 根据当前页大小查询
  const handleSizeChange = async (newPageSize: number) => {
    tableLoad.value = true
    pageSize.value = newPageSize
    await getByPage(pageNo.value, pageSize.value)
  }
  // 根据当前页码查询
  const handleCurrentChange = async (newPageNo: number) => {
    tableLoad.value = true
    pageNo.value = newPageNo
    await getByPage(pageNo.value, pageSize.value)
  }
  // 分页查询
  const getByPage = async (pageNo?: number, pageSize?: number) => {
    await queryByPage({ pageNo: pageNo, pageSize: pageSize })
      .then((response) => {
        tableData.value = response.data.records
        pageTotal.value = response.data.total
      })
      .catch((error) => {
        console.log(error)
      })
    tableLoad.value = false
  }

  // ------------------------------ 挂载 ------------------------------
  onMounted(() => {
    tableLoad.value = true
    // 初始化
    getByPage()
  })

  // ------------------------------ 返回值 ------------------------------
  return {
    pageNo,
    pageSizes,
    pageSize,
    pageTotal,
    tableData,
    tableLoad,
    handleCurrentChange,
    handleSizeChange,
    getByPage,
  }
}
